package com.augrain.microframework.web.base;

import com.augrain.microframework.core.util.IpUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.Map;

/**
 * api context
 */
@Getter
@Setter
@Builder
public class ApiContext {

    public static ThreadLocal<ApiContext> current = new ThreadLocal<>();
    /**
     * API协议号
     */
    private String api;
    /**
     * 服务端流水号
     */
    private String sid;
    /**
     * 客户端流水号
     */
    private String cid;
    /**
     * 全局流水号
     */
    private String gid;
    /**
     * 客户端类型
     */
    private String ctype;
    /**
     * 日志前缀
     */
    private String logKey;
    /**
     * 是否已经响应
     */
    private boolean responsed;
    /**
     * 参数
     */
    private Map params;
    /**
     * TOKEN
     */
    private String token;
    /**
     * 环境参数
     */
    private Map env;
    /**
     * 客户端IP
     */
    private String cip;
    /**
     * 客户端端口
     */
    private Integer cport;
    /**
     * request
     */
    private HttpServletRequest request;
    /**
     * response
     */
    private HttpServletResponse response;

    /**
     * 获取当前的apiContext
     *
     * @return
     */
    public static ApiContext getCurrent() {
        return current.get();
    }

    public void setAttribute(String key, Object value) {
        if (this.env == null) {
            this.env = new HashMap();
        }
        this.env.put(key, value);
    }

    public <T> T getAttribute(String key) {
        if (this.env == null) {
            return null;
        }
        return (T) this.env.get(key);
    }

    /**
     * 获取ip，
     */
    public String getClientIP() {
        if (this.cip == null) {
            this.cip = IpUtils.getRemoteIp(request);
        }
        return this.cip;
    }

    /**
     * 获取远程端口
     */
    public Integer getClientPort() {
        if (this.cport == null) {
            this.cport = IpUtils.getRemotePort(request);
        }
        return cport;
    }
}
